package de.unistuttgart.iaas.interaction.mail;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import de.unistuttgart.iaas.interaction.mail.database.MySQLAccess;
import de.unistuttgart.iaas.interaction.mail.util.CommonTools;
import de.unistuttgart.iaas.interaction.mail.util.ConfigFileHandler;
import de.unistuttgart.iaas.interaction.mail.util.LoggingFileHandler;

/**
 * This class builds a response string which will be returned.
 * @author Lina Sun
 * */
public class GetResponse 
{
	private static String configurationData = "C:/CommunicationService/configuration.conf";
	private static Logger logger = Logger.getLogger(GetResponse.class);
	
/**
 * 	The method checks the state for a request with mailid.
 * If the state is NEW, SENT, AWAIT_REPLY, REPLIED, string "noResponse" will be returned.
 * If the state is FINISHED, a valid response for the request will be returned.
 * If the state is TIMEOUT, FAILED, string "TIMEOUT" or "FAILED" will be returned.
 * If an Exception is thrown out, then string "ERROR" will be returned.
 * @param mailid
 * @return response
 */
	public static String getResponse(String mailid)
	{
		String response="noResponse";
		ArrayList list_response = new ArrayList();
		
		ConfigFileHandler config = new ConfigFileHandler(configurationData);
		LoggingFileHandler logFileHandler = new LoggingFileHandler(configurationData);
		
		Properties properties = new Properties();
		properties.setProperty("log4j.rootLogger", logFileHandler.getMailLogLevel()+", R");
		properties.setProperty("log4j.appender.R", logFileHandler.getMailAppender());
		properties.setProperty("log4j.appender.R.File", logFileHandler.getGetResponseLogFilePath());
		properties.setProperty("log4j.appender.R.MaxFileSize", logFileHandler.getMailLogFileSize() );
		properties.setProperty("log4j.appender.R.MaxBackupIndex", logFileHandler.getMailMaxBackupIndex());
		properties.setProperty("log4j.appender.R.layout", logFileHandler.getMailLayout());
		properties.setProperty("log4j.appender.R.layout.ConversionPattern", logFileHandler.getMailPattern());
		
		try
		{
			MySQLAccess dao = new MySQLAccess();
			Connection conn = dao.connDataBase(config);
			Statement statement1 = conn.createStatement();
			Statement statement2 = conn.createStatement();
			Statement statement3 = conn.createStatement();
			String table_sentmails = config.getTable_sentmails();
			String table_attachments = config.getTable_mailattachments();
					
	
			PropertyConfigurator.configure( properties );
	
			logger.info("---------------------GetResponseService------------------------");	
			
			ResultSet rs = statement1.executeQuery("select mail_state from maildb."+ config.getTable_sentmails()+" where mail_id='"+mailid+"'");
			while(rs.next())
			{
				//mail_state = FINISHED, get response for this request
				if(rs.getString(1).equalsIgnoreCase("FINISHED"))
				{
					ResultSet rsReply = statement2.executeQuery("select * from maildb."+config.getTable_mailbox()+" where mail_replyid='"+mailid+"' and mail_state='FINISHED'");
					
					while(rsReply.next())
					{
						for(int i=1; i<=10;i++)
						{
							list_response.add(rsReply.getString(i));
						}
						String mail_id = (String)list_response.get(0);
						//extract the response <response>...</response>
						String res = CommonTools.getResponse(list_response);
						response = res;
						
						//get attachment
						ResultSet rsAtt = statement3.executeQuery("select content from maildb."+config.getTable_mailattachments()+" where mail_id='"+mail_id+"'");
						String attachments ="";
						while(rsAtt.next())
						{
//							attachments = rsAtt.getBlob("content").toString()+"\n";
							InputStream a = rsAtt.getBlob("content").getBinaryStream();
							BufferedReader reader = new BufferedReader(new InputStreamReader(a));
						    StringBuilder sb = new StringBuilder();
						    String line = null;
						    while ((line = reader.readLine()) != null) {
						      sb.append(line + "\n");
						    }
						    a.close();
						    attachments = sb.toString();
							System.out.println(sb.toString());
						}
						
						logger.info("return a response of mail_ID: "+mailid+"("+res+")");
	
						if(!attachments.equals(""))
						{
							logger.info("With attachment:\n"+ attachments);
							response= response+" <attachment>"+attachments+ "</attachment>";
						}else
						{
							
						}
						
						
					}
				//if mail_state= TIMEOUT or FAILED,that means this request is closed, mail_state will be returned.
				}else if(rs.getString(1).equalsIgnoreCase("TIMEOUT")||rs.getString(1).equalsIgnoreCase("FAILED"))
				{
					response =rs.getString(1);
					//the request is not finished
				}else
				{
					response = "noResponse";
				}
			}
		}catch(Exception e)
		{
			logger.error("ERROR",e);			
		}
		return response;
	}
}

